package reader

import (
	"encoding/binary"

	"github.com/wzh200x/gateServer/network/message"
	"github.com/wzh200x/hyperNexus/hyperNexusCommon"
)

type HeaderCodec struct {
}

func (this *HeaderCodec) Encode(obj interface{}) (error, []byte) {
	me := hyperNexusCommon.NewMemoryStream(binary.BigEndian)
	hObj := obj.(*message.Header)
	var err error
	if err = me.WriteData(&hObj.Length); err != nil {
		return err, nil
	}
	if err = me.WriteData(&hObj.VerifyID); err != nil {
		return err, nil
	}
	if err = me.WriteData(&hObj.Opcode); err != nil {
		return err, nil
	}
	if err = me.WriteData(&hObj.OpcodeType); err != nil {
		return err, nil
	}
	if err = me.WriteData(&hObj.Masked); err != nil {
		return err, nil
	}
	if err = me.WriteData(&hObj.Mask); err != nil {
		return err, nil
	}
	return nil, me.GetData()
}

func (this *HeaderCodec) Decode(data []byte, obj interface{}) error {
	if len(data) == 0 {
		return nil
	}
	me := hyperNexusCommon.NewMemoryStreamWithBuff(binary.BigEndian, data, false)
	hObj := obj.(*message.Header)
	var err error
	if err = me.ReadData(&hObj.Length); err != nil {
		return err
	}
	if err = me.ReadData(&hObj.VerifyID); err != nil {
		return err
	}
	if err = me.ReadData(&hObj.Opcode); err != nil {
		return err
	}
	if err = me.ReadData(&hObj.OpcodeType); err != nil {
		return err
	}
	if err = me.ReadData(&hObj.Masked); err != nil {
		return err
	}
	if err = me.ReadData(&hObj.Mask); err != nil {
		return err
	}
	return nil
}
